import storage from 'store'
import { login, getInfo, logout, getCurrentUserBtns, getMessageInfoList } from '@/api/login'
import { getDepartList, getUserRoleAll, getSysDictCache, getAllDeptPostList } from '@/api/api'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { welcome } from '@/utils/util'
import { connectionSocket } from '@/utils/websocket'

const user = {
  state: {
    token: '',
    name: '',
    welcome: '',
    avatar: '',
    roles: [],
    info: {},
    sysMessageCount: 0,
    sysMessageList: {},
    departList: new Map(),
    roleList: new Map(),
    postionList: new Map(),
    sysDictList: {},
    btnPermissions: {}
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, { name, welcome }) => {
      state.name = name
      state.welcome = welcome
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_INFO: (state, info) => {
      state.info = info
    },
    SET_DEPART_LIST: (state, departList) => {
      state.departList = departList
    },
    SET_POSTION_LIST: (state, postionList) => {
      state.postionList = postionList
    },
    SET_ROLE_LIST: (state, roleList) => {
      state.roleList = roleList
    },
    SET_SYS_DICT_LIST: (state, sysDictList) => {
      state.sysDictList = sysDictList
    },
    SET_SYS_MESSAGE_COUNT: (state, sysMessageCount) => {
      state.sysMessageCount = sysMessageCount
    },
    SET_SYS_MESSAGE_LIST: (state, sysMessageList) => {
      state.sysMessageList = sysMessageList
    },
    SET_HAS_BTN_PERMISSIONS: (state, btnPermissions) => {
      state.btnPermissions = btnPermissions
    },
    GetDeparts (state) {
      // 获取部门列表
      getDepartList({}).then(res => {
        var map = new Map()
        res.result.data.map(x => {
          map.set(String(x.departCode), x)
        })
        state.departList = map
      })
    }
  },
  actions: {
    // 登录
    Login ({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo).then(response => {
          const result = response.result
          console.log(response)
          storage.set(ACCESS_TOKEN, result.token, 7 * 24 * 60 * 60 * 1000)
          commit('SET_TOKEN', result.token)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    GetDeparts ({ commit }) {
      commit('GetDeparts')
    },
    // 获取用户信息
    GetInfo ({ commit }) {
      return new Promise((resolve, reject) => {
        getInfo().then(response => {
          const result = response.result
          if (result.accountInfo) {
            commit('SET_INFO', result.accountInfo)
          } else {
            reject(new Error('getInfo: roles must be a non-null array !'))
          }
          commit('SET_NAME', { name: result.accountInfo.companyName, welcome: welcome() })
          commit('SET_AVATAR', result.accountInfo.avatar)

          commit('GetDeparts')

          // 获取岗位列表
          getAllDeptPostList({}).then(res => {
            var map = new Map()
            res.result.data.map(x => {
              map.set(Number(x.id), x.name)
            })
            commit('SET_POSTION_LIST', map)
          })

          // 获取所有权限列表
          getUserRoleAll({}).then(res => {
            var map = new Map()
            res.result.data.map(x => {
              map.set(Number(x.id), x)
            })
            commit('SET_ROLE_LIST', map)
          })
          // 获取字典
          getSysDictCache({}).then(res => {
            commit('SET_SYS_DICT_LIST', res.result.data)
          })
          // 可以操作的按钮
          getCurrentUserBtns().then(res => {
            commit('SET_HAS_BTN_PERMISSIONS', res.result.data)
          })

          getMessageInfoList().then(res => {
            commit('SET_SYS_MESSAGE_COUNT', res.result.dataCount)
            commit('SET_SYS_MESSAGE_LIST', res.result.dataMessageList)
            connectionSocket()
          })
          // // 消息信息
          // getMessageInfoList().then(res => {emit
          //   commit('SET_SYS_MESSAGE_LIST', res.result.data)
          // })
          // 获取岗位列表
          // getRoleList({pageNumber: 1, pageSize: 100}).then(res => {
          //   if (res.data.code == '0000') {
          //     commit('setRoleList', res.data.result.pageData.records)
          //   }
          // })
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    Logout ({ commit, state }) {
      return new Promise((resolve) => {
        logout(state.token).then(() => {
          resolve()
        }).catch(() => {
          resolve()
        }).finally(() => {
          commit('SET_TOKEN', '')
          storage.remove(ACCESS_TOKEN)
        })
      })
    }

  }
}

export default user
